﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using WX.WMS.DataModel;
using WX.WMS.Common;
using WX.WMS.BLL;

public partial class InStock_InStockDetail : PageBase
{
    private string action
    {
        get
        {
            if (ViewState["action"] == null) return "";
            else return ViewState["action"].ToString();
        }
        set { ViewState["action"] = value; }
    }
    private string ID
    {
        get
        {
            if (ViewState["OutStockID"] == null) return "";
            else return ViewState["OutStockID"].ToString();
        }
        set { ViewState["OutStockID"] = value; }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
       // btnReport.Attributes.Add("onclick", "this.form.target='_newName'");
        if (!IsPostBack)
        {
            ViewState["EditItem"] = false;
            ID = "";
            action = "";
            Client.DataSource = new ClientBLL().GetClientList();
            Client.DataBind();
            CommomMethod.BindEnumForDropdwonList(this.Type, typeof(Enumerations.InStockType));
            CommomMethod.BindEnumForDropdwonList(this.StockType, typeof(Enumerations.StockType));
            Stock.DataSource = new StoreHouseBLL().GetStockList();
            Stock.DataBind();
            BoundAreaList();
            BoundFloorList();
            //Area.DataSource = new StoreHouseBLL().GetStockAreaList();
            //Area.DataBind();
            //Floor.DataSource = new FloorBLL().GetFloorList();
            //Floor.DataBind();
            action = Request.QueryString["action"];
            if (action == null || action == "" || action.ToString() == "add")
            {
                action = "add";
                lblTitle.Text = "添加入库单";
                CreateTime.Text = DateTime.Now.ToShortDateString();

                this.btnReport.Visible = false;
                this.btnReport2.Visible = false;

            }
            else if (action == "edit")
            {
                lblTitle.Text = "编辑入库单";
                ID = Request.QueryString["ID"];
                DetailDiv.Visible = true;
                MainDelete.Visible = true;
                MainFinish.Visible = true;
                this.MainSave.Visible = true;
                this.btnReport.Visible = false;
                this.btnReport2.Visible = false;

                T_INSTOCK InStock = new InStockBLL().GetInStockByID(ID);
                this.CreateTime.Text = InStock.CREATE_TIME.Value.ToShortDateString();
                this.InStockID.Text = InStock.INSTOCK_ID;
                this.ApplyID.Text = InStock.APPLY_ID;
                this.EAccount.Text = InStock.E_ACCOUNT;
                this.CarNO.Text = InStock.Car_NO;
                this.RawID.Text = InStock.RawID;
                this.InStockDate.Text = InStock.INSTOCK_DATE.Value.ToShortDateString();
                this.AllRemark.Text = InStock.Remark;
                ListItem Item = Client.Items.FindByValue(InStock.CLIENT_ID.ToString());
                Client.SelectedIndex = Client.Items.IndexOf(Item);
                this.Type.SelectedIndex = InStock.TYPE;
                SearchResult.DataSource = InStock.T_INSTOCK_ITEMs;
                SearchResult.DataBind();
            }
            else
            {
                lblTitle.Text = "查看入库单";
                ID = Request.QueryString["ID"];
                DetailDiv.Visible = false;
                MainDelete.Visible = false;
                MainFinish.Visible = false;
                MainSave.Visible = false;
                T_INSTOCK InStock = new InStockBLL().GetInStockByID(ID);
                this.CreateTime.Text = InStock.CREATE_TIME.Value.ToShortDateString();
                this.InStockID.Text = InStock.INSTOCK_ID;
                this.ApplyID.Text = InStock.APPLY_ID;
                this.EAccount.Text = InStock.E_ACCOUNT;
                this.RawID.Text = InStock.RawID;
                this.CarNO.Text = InStock.Car_NO;
                this.InStockDate.Text = InStock.INSTOCK_DATE.Value.ToShortDateString();
                this.AllRemark.Text = InStock.Remark;
                ListItem Item = Client.Items.FindByValue(InStock.CLIENT_ID.ToString());
                Client.SelectedIndex = Client.Items.IndexOf(Item);
                this.Type.SelectedIndex = InStock.TYPE;
                SearchResult.DataSource = InStock.T_INSTOCK_ITEMs;
                SearchResult.DataBind();
                SearchResult.Columns[7].Visible = false;

            }

        }
        CreateTime.ReadOnly = true;
        this.InStockID.Attributes["readonly"] = "readonly";
        InStockDate.Attributes["readonly"] = "readonly"; 
        this.ProductedDate.Attributes["readonly"] = "readonly";
        //this.BarCode.Attributes["readonly"] = "readonly";
        this.form1.Target = "_self";
       // ProductedDate.Attributes["readonly"] = "readonly";
       // OtherStoreDate.Attributes["readonly"] = "readonly";
    }

    protected string GetInStockID()
    {
        string inStockID = "1" + DateTime.Now.ToString("yyyyMMdd");
        InStockBLL inStockBLL = new InStockBLL();

        T_INSTOCK inStock = inStockBLL.GetInStockList().Where(t=>t.INSTOCK_ID.Substring(1,8) == DateTime.Now.ToString("yyyyMMdd")).OrderByDescending(y=>y.INSTOCK_ID).FirstOrDefault();
        if (inStock != null)
        {
            int no = Int32.Parse(inStock.INSTOCK_ID.Substring(9).TrimStart(new char[] { '0' })) + 1;
            inStockID += no.ToString().PadLeft(3, '0');
        }
        else
        {
            inStockID += "001";
        }

        return inStockID;
    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        T_PRODUCT Product = new ProductBLL().GetProductByID(StoreID.Text.Trim());
        if (Product != null)
        {
            this.ProductsName.Value = Product.NAME;
            this.ProductsID.Value = Product.ID.ToString();
            if (Product.T_UNIT1 != null)
            {
                this.NewWeightUnit.Text = this.GrossWeightUnit.Text = Product.T_UNIT1.NAME;
            }
            if (Product.T_UNIT != null)
            {
                this.PacketQtyUnit.Text = this.PacketQty2Unit.Text = Product.T_UNIT.NAME;
            }
            //SetBarCode();

            
        }
    }
    private string GetBarCode()
    {
                BaseDAO dao = new BaseDAO();
            var source = from t in dao.T_INSTOCK_ITEMs
                         where t.INSTOCK_ID.ToString() == ID
                         orderby t.T_PRODUCT_DETAIL.BAR_CODE descending
                         select t;
            if (source == null || source.Count() == 0||string.IsNullOrEmpty(source.First().T_PRODUCT_DETAIL.BAR_CODE))
            {
                return this.InStockID.Text + "0001";
            }
            else
            { 
                long  result;
                if (!long.TryParse(source.First().T_PRODUCT_DETAIL.BAR_CODE, out result))
                {
                    return this.InStockID.Text + "0001";
                }
                else
                {
                    return Convert.ToString(result + 1);
                }

            }
    }
    protected void MainSave_Click(object sender, EventArgs e)
    {
        InStockBLL BllInStock = new InStockBLL();

        if (action == "add" && string.IsNullOrEmpty(ID))
        {
            string NewInStockID = string.Empty;
            this.InStockID.Text = GetInStockID();

            T_INSTOCK InStock = new T_INSTOCK();
            InStock.APPLY_ID = this.ApplyID.Text.Trim();
            InStock.CLIENT_ID = new Guid(this.Client.SelectedValue);
            //更新的时候不要更新createtime
            //InStock.CREATE_TIME = DateTime.Now;
            InStock.CREATOR_ID = this.UserInfo.ID;
            InStock.E_ACCOUNT = EAccount.Text.Trim();
            InStock.INSTOCK_DATE = DateTime.Parse(this.InStockDate.Text);
            InStock.INSTOCK_ID = this.InStockID.Text.Trim();
            InStock.TYPE=Convert.ToInt32(this.Type.SelectedValue);
            InStock.CREATE_TIME = DateTime.Parse(this.CreateTime.Text);
            InStock.Car_NO = this.CarNO.Text.Trim();
            InStock.RawID = this.RawID.Text.Trim();
            InStock.Remark = this.AllRemark.Text;

            BllInStock.AddInStock(InStock, out NewInStockID);
            ID = NewInStockID;
            DetailDiv.Visible = true;
            MainDelete.Visible = true;
            MainFinish.Visible = true;
            this.btnReport.Visible = true;
            this.btnReport2.Visible = true;
        }
        else 
        {
            T_INSTOCK InStock = BllInStock.GetInStockByID(ID);

            InStock.APPLY_ID = this.ApplyID.Text.Trim();
            InStock.CLIENT_ID = new Guid(this.Client.SelectedValue);
            InStock.CREATE_TIME = DateTime.Now;
            InStock.CREATOR_ID = this.UserInfo.ID;
            InStock.E_ACCOUNT = EAccount.Text.Trim();
            InStock.INSTOCK_ID = this.InStockID.Text.Trim();
            InStock.INSTOCK_DATE = DateTime.Parse(this.InStockDate.Text);
            InStock.TYPE = Convert.ToInt32(this.Type.SelectedValue);
            InStock.CREATE_TIME = DateTime.Parse(this.CreateTime.Text);
            InStock.RawID = this.RawID.Text.Trim();
            InStock.Car_NO = this.CarNO.Text.Trim();
            InStock.Remark = this.AllRemark.Text;

            BllInStock.UpdateInStock(InStock);
        }

    }
    protected void MainDelete_Click(object sender, EventArgs e)
    {
        new InStockBLL().DeleteInStock(ID);
       // CreateTime.Text = string.Empty;
        InStockID.Text = string.Empty;
        ApplyID.Text = string.Empty;
        EAccount.Text = string.Empty;
        InStockDate.Text = string.Empty;
        RawID.Text = string.Empty;
        CarNO.Text = string.Empty;
        DetailDiv.Visible = false;
        MainDelete.Visible = false;
        MainFinish.Visible = false;
        SearchResult.DataSource = null;
        SearchResult.DataBind();
        ID = "";
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        if (string.IsNullOrEmpty(ProductsID.Value))
        {
            ShowMessage("请选择商品");
            return;
        }

        T_INSTOCK_ITEM Item;
        T_PRODUCT_DETAIL Detail;
        ProductDetailBLL BllProductDetail=new ProductDetailBLL();
        InStockItemItemBLL BllStockItemItem = new InStockItemItemBLL();
        if ((bool)ViewState["EditItem"] == false)
        {
            Item = new T_INSTOCK_ITEM();
            Detail = new T_PRODUCT_DETAIL();
        }
        else
        {
            Item = BllStockItemItem.GetInStockItemByID(SearchResult.SelectedValue.ToString());
            Detail = BllProductDetail.GetProductDetailByID(ViewState["ProductDetailID"].ToString());
        }
        
        if (string.IsNullOrEmpty(this.BarCode.Value.Trim()))
        {
            //ShowMessage("条形码不能为空");
            //return;
            Detail.BAR_CODE = GetBarCode();
        }
        else {

            Detail.BAR_CODE = this.BarCode.Value.Trim();
        }
        if (string.IsNullOrEmpty(this.Model.Value.Trim()))
        {
            //ShowMessage("型号不能为空");
            //return;
            Detail.MODEL = null;
        }
        else
        {
            Detail.MODEL = this.Model.Value.Trim();
        }
        if (string.IsNullOrEmpty(this.Standard.Value.Trim()))
        {
            //ShowMessage("规格不能为空");
            //return;
            Detail.STANDARD = null;
        }
        else
        {
            Detail.STANDARD = this.Standard.Value.Trim();
        }
        if (string.IsNullOrEmpty(this.KeyStandard.Value.Trim()))
        {
            //ShowMessage("关键规格不能为空");
            //return;
            Detail.KeyStandard = null;
        }
        else
        {
            Detail.KeyStandard = this.KeyStandard.Value.Trim();
        }
        if (string.IsNullOrEmpty(this.Origin.Value.Trim()))
        {
            //ShowMessage("产地不能为空");
            //return;
            Detail.ORIGIN = null;
        }
        else
        {
            Detail.ORIGIN = this.Origin.Value.Trim();
        }
        if (string.IsNullOrEmpty(this.Brand.Value.Trim()))
        {
            //ShowMessage("牌子不能为空");
            //return;
            Detail.BRAND = null;
        }
        else
        {
            Detail.BRAND = this.Brand.Value.Trim();
        }

        if (string.IsNullOrEmpty(this.Size.Value.Trim()))
        {
            //ShowMessage("尺寸不能为空");
            //return;
            Detail.SIZE = null;
        }
        else
        {
            Detail.SIZE = this.Size.Value.Trim();
        }
        if (string.IsNullOrEmpty(this.LotNumber.Value.Trim()))
        {
            //ShowMessage("主批次不能为空");
            //return;
            Detail.LOT_NUMBER = null;
        }
        else
        {
            Detail.LOT_NUMBER = this.LotNumber.Value.Trim();
        }
        if (string.IsNullOrEmpty(this.SubLotNumber.Value.Trim()))
        {
            //ShowMessage("次批次不能为空");
            //return;
            Detail.SUB_LOT_NUMBER = null;
        }
        else
        {
            Detail.SUB_LOT_NUMBER = this.SubLotNumber.Value.Trim();
        }
        if (string.IsNullOrEmpty(this.SupplyLotNumber.Value.Trim()))
        {
            //ShowMessage("供应商批次不能为空");
            //return;
            Detail.SupplyLotNumber = null; ;
        }
        else
        {
            Detail.SupplyLotNumber = this.SupplyLotNumber.Value.Trim();
        }
        if (string.IsNullOrEmpty(this.BigClass.Value.Trim()))
        {
            //ShowMessage("货物大类不能为空");
            //return;
            Detail.BigClass = null;
        }
        else
        {
            Detail.BigClass = this.BigClass.Value.Trim();
        }

        if (string.IsNullOrEmpty(this.ProductedDate.Text.Trim()))
        {
            //ShowMessage("原始日期不能为空");
            //return;
            Detail.PRODUCTED_DATE = null;
        }
        else
        {
            Detail.PRODUCTED_DATE = DateTime.Parse(this.ProductedDate.Text.Trim());
        }

        if (string.IsNullOrEmpty(this.PacketNO.Value.Trim()))
        {
            //ShowMessage("柜号不能为空");
            //return;
            Detail.PACKET_NO = null;
        }
        else
        {
            Detail.PACKET_NO = this.PacketNO.Value.Trim();
        }
        //if (string.IsNullOrEmpty(this.ProductedDate.Text.Trim()))
        //{
        //    ShowMessage("生成日期不能为空");
        //    return;
        //}
        //else
        //{
        //    Detail.PRODUCTED_DATE =DateTime.Parse(this.ProductedDate.Text.Trim());
        //}
        if (string.IsNullOrEmpty(this.Floor.SelectedValue))
        {
            ShowMessage("层不能为空");
            return;
        }
        else
        {
            Item.FLOOR_ID = new Guid(this.Floor.SelectedValue);
        }
        if (string.IsNullOrEmpty(this.StockType.SelectedValue))
        {
            ShowMessage("库存类型不能为空");
            return;
        }
        else
        {
            Detail.STOCK_TYPE = Convert.ToInt32(this.StockType.SelectedValue);
        }
        //if (string.IsNullOrEmpty(this.OtherStoreDate.Text.Trim()))
        //{
        //    ShowMessage("进仓日期不能为空");
        //    return;
        //}
        //else
        //{
        //    Detail.OTHER_STOCK_DATE = DateTime.Parse(this.OtherStoreDate.Text.Trim());
        //}
        if (string.IsNullOrEmpty(this.NetWeight.Value.Trim()))
        {
            ShowMessage("净重不能为空");
            return;
        }
        else
        {
            Item.NET_WEIGHT = Convert.ToDouble(this.NetWeight.Value.Trim());
        }
        if (string.IsNullOrEmpty(this.GrossWeight.Value.Trim()))
        {
            ShowMessage("毛重不能为空");
            return;
        }
        else
        {
            Item.GROSS_WEIGHT = Convert.ToDouble(this.GrossWeight.Value.Trim());
        }
        if (string.IsNullOrEmpty(this.PacketQty.Value.Trim()))
        {
            ShowMessage("大件数不能为空");
            return;
        }
        else
        {
            Item.PACKET_QTY = Convert.ToDouble(this.PacketQty.Value.Trim());
        }
        if (string.IsNullOrEmpty(this.PacketQty2.Value.Trim()))
        {
            ShowMessage("小件数不能为空");
            return;
        }
        else
        {
            Item.PACKET_QTY2 = Convert.ToDouble(this.PacketQty2.Value.Trim());
        }
        Item.REMARK = Remark.Value.Trim();       
        Item.INSTOCK_ID = new Guid(ID);
        Detail.PRODUCT_ID = new Guid(ProductsID.Value);
        Detail.InStock_Date = DateTime.Parse(this.InStockDate.Text);
        Detail.ClientID=new Guid(this.Client.SelectedValue);
        
        string existID=string.Empty;
        if ((bool)ViewState["EditItem"] == false)
        {
            if (BllProductDetail.IsExisted(Detail, out existID))
            {
                Item.PRODUCT_DETAIL_ID = new Guid(existID);
                BllStockItemItem.AddInStockItem(Item);
            }
            else
            {
                Item.ID = Guid.NewGuid();
                Detail.T_INSTOCK_ITEMs.Add(Item);
                BllProductDetail.AddProductDetail(Detail);
            }
        }
        else {           
                BllStockItemItem.UpdateInStockItem(Item);            
                BllProductDetail.UpdateProductDetail(Detail);           
        }

        BindGridView();

        this.BarCode.Value = "";

        SearchResult.SelectedIndex = -1;
        ViewState["EditItem"] = false;
        ShowMessage("保存成功");
        //SetBarCode();
    }

    protected void BindGridView()
    {
        InStockBLL Bll = new InStockBLL();
 
        Bll.AddOrderByCondition(ViewState["StationSortOrder"] + " " + ViewState["StationOrderDire"]);
        SearchResult.DataSource = Bll.GetInStockDetailByStockID(ID);
        SearchResult.DataBind();
    }

    protected void MainFinish_Click(object sender, EventArgs e)
    {
        if (action == null || action == "" || action.ToString() == "add")
        {
            Response.Redirect("InStockDetail.aspx?action=add");
        }
        else
        {
            Response.Redirect("InStockManager.aspx");
        }

    }
    protected void SearchResult_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string ItemID = SearchResult.DataKeys[e.RowIndex]["ID"].ToString();
        InStockItemItemBLL BllInStockItem = new InStockItemItemBLL();
        BllInStockItem.DeleteInStockItem(ItemID);

        BindGridView();
    }
    //protected void MainFinish0_Click(object sender, EventArgs e)
    //{
    //    Response.Redirect("InStockManager.aspx");
    //}
    protected void Stock_SelectedIndexChanged(object sender, EventArgs e)
    {
        BoundAreaList();
        BoundFloorList();
    }
    protected void Area_SelectedIndexChanged(object sender, EventArgs e)
    {
        BoundFloorList();
    }

    protected void BoundAreaList()
    {
        var source = new StoreHouseBLL().GetStockAreaList();
        Area.DataSource = source.Where(t => t.STOCK_ID.ToString() == Stock.SelectedValue);
        Area.DataBind();
    }

    protected void BoundFloorList()
    {
        var source = new FloorBLL().GetFloorList();
        Floor.DataSource = source.Where(t => t.T_STOCK_AREA.AREA_ID.ToString() == Area.SelectedValue);
        Floor.DataBind();
    }
    protected void btnReport_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(this.ID)) return;
       // Response.Redirect("~/report/ReportView.aspx?type=instock&ID="+ID);    
        string js = "<script language='javascript'>window.open(\"../report/ReportView.aspx?type=instockdetail&ID=" + ID + "\",\"_blank\");</script>";
        Response.Write(js);
      //  Response.Redirect("~/report/ReportView.aspx?type=instockdetail&ID=" + ID);    
    }
    protected void btnReport2_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(this.ID)) return;
        // Response.Redirect("~/report/ReportView.aspx?type=instock&ID="+ID);    
        string js = "<script language='javascript'>window.open(\"../report/ReportView.aspx?type=instocknofloor&ID=" + ID + "\",\"_blank\");</script>";
        Response.Write(js);
    }
    protected void SearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.SearchResult.PageIndex = e.NewPageIndex;
        BindGridView();
    }
    protected void SearchResult_Sorting(object sender, GridViewSortEventArgs e)
    {
        string sortExpression = e.SortExpression;
        if (Convert.ToString(ViewState["StationSortOrder"]) == sortExpression)
        {
            if (Convert.ToString(ViewState["StationOrderDire"]) == "Desc")
                ViewState["StationOrderDire"] = "Asc";
            else
                ViewState["StationOrderDire"] = "Desc";
        }
        else
        {
            ViewState["StationSortOrder"] = sortExpression;
        }
        BindGridView();
    }

    protected string GetStockPosition(T_INSTOCK_ITEM item)
    {
        return item.T_FLOOR.T_STOCK_AREA.T_STOCK.STOCK_NAME + "->" + item.T_FLOOR.T_STOCK_AREA.AREA_NAME + "->" + item.T_FLOOR.FloorName;

    }
    protected void SearchResult_SelectedIndexChanged(object sender, EventArgs e)
    {
        //ShowMessage(SearchResult.SelectedValue.ToString());
        T_INSTOCK_ITEM item = new InStockItemItemBLL().GetInStockItemByID(SearchResult.SelectedValue.ToString());
        this.ProductsID.Value = item.T_PRODUCT_DETAIL.PRODUCT_ID.ToString();
        this.BarCode.Value = item.T_PRODUCT_DETAIL.BAR_CODE;
        this.Model.Value = item.T_PRODUCT_DETAIL.MODEL;
        this.Standard.Value = item.T_PRODUCT_DETAIL.STANDARD;
        this.KeyStandard.Value = item.T_PRODUCT_DETAIL.KeyStandard;
        this.Origin.Value = item.T_PRODUCT_DETAIL.ORIGIN;
        this.Brand.Value = item.T_PRODUCT_DETAIL.BRAND;
        this.Size.Value = item.T_PRODUCT_DETAIL.SIZE;
        this.LotNumber.Value = item.T_PRODUCT_DETAIL.LOT_NUMBER;
        this.SubLotNumber.Value = item.T_PRODUCT_DETAIL.SUB_LOT_NUMBER;
        this.SupplyLotNumber.Value = item.T_PRODUCT_DETAIL.SupplyLotNumber;
        this.BigClass.Value = item.T_PRODUCT_DETAIL.BigClass;
        this.ProductsName.Value = item.T_PRODUCT_DETAIL.T_PRODUCT.NAME;
        if (item.T_PRODUCT_DETAIL.PRODUCTED_DATE != null)
            this.ProductedDate.Text = item.T_PRODUCT_DETAIL.PRODUCTED_DATE.Value.ToString();

        this.PacketNO.Value = item.T_PRODUCT_DETAIL.PACKET_NO;

        var areaId = new FloorBLL().GetFloorByID(item.FLOOR_ID.ToString()).AREA_ID;
        var stockId = new StoreHouseBLL().GetStockAreaByID(areaId.Value.ToString()).STOCK_ID;

        this.Stock.SelectedValue = stockId.Value.ToString();
         BoundAreaList();
         this.Area.SelectedValue = areaId.Value.ToString();
         BoundFloorList();

        this.Floor.SelectedValue = item.FLOOR_ID.ToString();
        if( item.T_PRODUCT_DETAIL.STOCK_TYPE!=null)
         this.StockType.SelectedValue = item.T_PRODUCT_DETAIL.STOCK_TYPE.Value.ToString();


        this.NetWeight.Value = item.NET_WEIGHT.Value.ToString();
        this.GrossWeight.Value = item.GROSS_WEIGHT.Value.ToString();
        this.PacketQty.Value = item.PACKET_QTY.Value.ToString();
        this.PacketQty2.Value = item.PACKET_QTY2.Value.ToString();
        this.Remark.Value = item.REMARK;
        ViewState["ProductDetailID"] = item.T_PRODUCT_DETAIL.ID.ToString();
        ViewState["EditItem"] = true;
    }
}
